package com.cebbank.yyi.springbootapp.jingtang.test;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.cebbank.yyi.springbootapp.jingtang.dao.*;
import com.cebbank.yyi.springbootapp.jingtang.dto.*;
import com.cebbank.yyi.springbootapp.jingtang.entity.*;
import com.cebbank.yyi.springbootapp.jingtang.enums.*;
import com.cebbank.yyi.springbootapp.jingtang.json.EsBO;
import com.cebbank.yyi.springbootapp.jingtang.json.MenuBO;
import com.cebbank.yyi.springbootapp.jingtang.utils.FileUtil;
import com.cebbank.yyi.springbootapp.jingtang.utils.RequestUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.ResponseBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @description:
 * @author: yyi
 * @date: 2024/8/25 10:40
 * @version: 1.0
 **/
@Component
@Slf4j
public class ApplyMappingService {

    @Autowired
    private RcDocDao rcDocDao;

    @Autowired
    private RcDocAuthorDao rcDocAuthorDao;

    @Autowired
    private RcDocProductionDao rcDocProductionDao;

    @Autowired
    private RcDocBaseDao rcDocBaseDao;

    @Autowired
    private RcDocManagerDocRegulationsDao rcDocManagerDocRegulationsDao;

    @Autowired
    private TDocCateDao tDocCateDao;

    @Autowired
    private RcDirectoryDao rcDirectoryDao;

    @Autowired
    private ApprovalRecordDAO approvalRecordDAO;

    DocType docMenuType1;

    private final static int retryTimes = 5;


    public ResultDto applyMapping(String json, String token, MenuBO menuBo, ConditionParams conditionParams) throws Exception {
        Gson gson = new Gson();
        ResultDto resultDto = new ResultDto();
        ResponseDTO testBean = gson.fromJson(json, ResponseDTO.class);
        if (testBean.getData() == null) {
            log.error("获取的data域为null-{}, {}", menuBo, conditionParams);
            return null;
        }
        resultDto.setSyncFailed(false);
        resultDto.setResponseDTO(testBean);
        DocType docMenuType = DocType.fromDesc(menuBo.getType());
        List<ResponseDTO.DataDTO.PageDTO.RecordsDTO> records = testBean.getData().getPage().getRecords();
        for (ResponseDTO.DataDTO.PageDTO.RecordsDTO record : records) {
//            if (isSkip(record.getId())) {
//                System.err.println("跳过处理该文件");
//                return null;
//            }
            for (int i = 0; i < retryTimes; i++) {
                String rcId = record.getId() + FileUtil.getVersion();
                RcDoc existRcDoc = null;
                try {
                    existRcDoc = rcDocDao.queryById(rcId);
                } catch (Exception e) {
                    log.error("{}, {}, 查询rcDoc失败：{}", menuBo, conditionParams, rcId, e);
                }
                if (null != existRcDoc) {
                    if (record.getFileLastId() != null) {
                        String fileLastId = record.getFileLastId();
                        if (fileLastId.contains(",")) {
                            String[] fileLastIds = fileLastId.split(",");
                            for (String lastId : fileLastIds) {
                                RcDocBase rcDocBase = new RcDocBase();
                                rcDocBase.setDocId(rcId);
                                rcDocBase.setBaseId(lastId + FileUtil.getVersion());
                                rcDocBase.setBaseType(DocBaseTypeEnum.FILE_LAST_ID.getName());
                                rcDocBase.setId(FileUtil.getSnowId());
                                try {
                                    rcDocBaseDao.insert(rcDocBase);
                                } catch (Exception e) {
                                    log.error("{}, {}, 上一版本文件-插入rcBaseDao表失败：{}", menuBo, conditionParams, rcDocBase.toString(), e);
                                }
                            }
                        }
                        // 如果fileLastId不为null，向DocBase表中插入一条REPEAL_PARENT_DOC记录
                    }
                    String directoryId;
                    Integer menuType = Integer.valueOf(menuBo.getMenuType());

                    String directoryType = docMenuType.getDirectoryType();
                    String parentName = tDocCateDao.getParentName(String.valueOf(menuType));

                    if (Objects.equals(menuBo.getType(), "生产技术文件")) {
                        String processSetId = record.getProcessSetId();
                        String processSetName;
                        if (StrUtil.isNotEmpty(processSetId)) {
                            processSetName = tDocCateDao.getCategoryNameString(processSetId);
                        } else {
                            System.err.printf("当前文件属于[%s]-[%s]-[%s]，processSetId为空！\n", menuBo.getType(), menuBo.getMenuType(), menuBo.getName());
                            processSetName = menuBo.getName();
                            System.err.printf(processSetName);
                        }
                        List<RcDirectory> directoryIdByNames;
                        if (Objects.equals(menuBo.getType(), "生产技术文件")) {
                            directoryIdByNames = rcDirectoryDao.getDirectoryIdByNameSCJS(processSetName);
                        } else {
                            directoryIdByNames = rcDirectoryDao.getDirectoryIdByName(processSetName, directoryType);
                        }
                        RcDirectory finalDirectory2;
                        if (CollUtil.isEmpty(directoryIdByNames)) {
                            System.err.printf("%s未匹配到directory!!!\n", record.getFileName());
                            directoryId = docMenuType.getDirectoryId();
                        } else {
                            if (directoryIdByNames.size() > 1) {
                                System.err.printf("存在多条directory记录：%s，根据上一级目录[%s]确定最终子目录结构！\n", directoryIdByNames.toString(), parentName);
                                RcDirectory directoryIdByNameAndParentName;
                                if (parentName.equals("工艺变更申请表")) {
                                    parentName = "工艺变更单申请表";
                                }
                                if (Objects.equals(parentName, "PFMEA") || Objects.equals(parentName, "工艺变更单")) {
                                    directoryIdByNameAndParentName = rcDirectoryDao.getDirectoryIdEqualNameAndParentName(processSetName, directoryType, parentName);
                                } else {
                                    directoryIdByNameAndParentName = rcDirectoryDao.getDirectoryIdByNameAndParentName(processSetName, directoryType, parentName);
                                }
                                System.err.printf("根据上一级目录查询成功：[%s]", directoryIdByNameAndParentName.toString());
                                finalDirectory2 = directoryIdByNameAndParentName;
                            } else {
                                finalDirectory2 = directoryIdByNames.get(0);
                            }
//                                rcDoc.setDirectoryId(finalDirectory2.getId());
//                                String treePath = finalDirectory2.getTreePath();
//                                System.err.printf("当前文件属于[%s]-[%s]-[%s]，目录树为[%s]", menuBo.getType(), menuBo.getMenuType(), menuBo.getName(), treePath);
                            directoryId = finalDirectory2.getId();
                        }
                        existRcDoc.setDirectoryId(directoryId);

                    }

                    if (StrUtil.isNotEmpty(record.getDestroyFileId())) {
                        String fileLastId = record.getDestroyFileId();
                        if (fileLastId.contains(",")) {
                            String[] fileLastIds = fileLastId.split(",");
                            for (String lastId : fileLastIds) {
                                RcDocBase rcDocBase = new RcDocBase();
                                rcDocBase.setDocId(rcId);
                                rcDocBase.setBaseId(lastId + FileUtil.getVersion());
                                rcDocBase.setBaseType(DocBaseTypeEnum.FILE_LAST_ID.getName());
                                rcDocBase.setId(FileUtil.getSnowId());
                                try {
                                    rcDocBaseDao.insert(rcDocBase);
                                } catch (Exception e) {
                                    log.error("{}, {},同时废止文件-插入rcBaseDao表失败：{}", menuBo, conditionParams, rcDocBase.toString(), e);
                                }
                                System.out.printf("同时废止文件ID不为空，新增rcDocBase表记录：%s", rcDocBase.toString());
                            }
                        }
                    }
                    DownloadFileInfo downloadFileInfo = new DownloadFileInfo();
                    String fileNameStr = record.getFileName() + ".docx";
                    downloadFileInfo.setFilePath(record.getFilePath());
                    downloadFileInfo.setFileName(fileNameStr);
                    String fileName = FileUtil.downloadFile(token, downloadFileInfo, String.valueOf(record.getId()));
                    existRcDoc.setDocName(fileName.substring(0, fileName.lastIndexOf(".")));
                    if (record.getDueDate() != null) {
                        String dueDate = record.getDueDate().toString().split(" ")[0];
                        existRcDoc.setExpireDate(dueDate);
                    }
                    rcDocDao.update(existRcDoc);
                    FileOperatorParams fileOperatorParams = new FileOperatorParams();
                    fileOperatorParams.setDocName(fileName);
                    fileOperatorParams.setDocId(rcId);
                    fileOperatorParams.setDirectoryType(existRcDoc.getDirectoryType());
                    boolean isUploaded = FileUtil.uploadMainFile(fileOperatorParams, String.valueOf(record.getId()));
                    if (!isUploaded) {
                        log.error("上传主文档-{}失败：类型{},{}", record.getFileName(), menuBo, conditionParams);
                    }
//                    // 根据老系统的文件id获取附件信息并入库
                    getAnnexFilesAndUpload(String.valueOf(record.getId()), token, rcId, menuBo, conditionParams, record.getFileName());
//                    // 同步es
                    RequestUtil.syncEs(rcId);
                    break;
                }
                RcDoc rcDoc = new RcDoc();
                // 最底层目录id
                Integer menuType = Integer.valueOf(menuBo.getMenuType());
                String menuName = menuBo.getName();
                String directoryType = docMenuType.getDirectoryType();
                // 顶层目录名称
                String directoryTypeName = docMenuType.getDesc();
                // 老系统底层目录名称
                String directoryName = tDocCateDao.getCategoryNameString(String.valueOf(menuType));
                // 老系统底层目录上级目录名称
                String parentName = tDocCateDao.getParentName(String.valueOf(menuType));
                String directoryId;
                // 如果文件中读取的名称是下面2种，直接从枚举里取值
                if (Objects.equals(menuName, "管理手册") || Objects.equals(menuName, "部门级规章制度")) {
                    directoryId = docMenuType.getDirectoryId();
                } else {
                    if (Objects.equals(menuBo.getType(), "公司级规章制度")) {
                        String processSetId = record.getProcessSetId();
                        String processSetName;
                        if (StrUtil.isNotEmpty(processSetId)) {
                            processSetName = tDocCateDao.getCategoryNameString(processSetId);
                        } else {
                            System.err.printf("当前文件属于[%s]-[%s]-[%s]，processSetId为空！", menuBo.getType(), menuBo.getMenuType(), menuBo.getName());
                            processSetName = menuBo.getName();
                        }
                        List<RcDirectory> directoryIdByNames = rcDirectoryDao.getDirectoryIdByName(processSetName, directoryType);
                        RcDirectory finalDirectory2;
                        if (CollUtil.isEmpty(directoryIdByNames)) {
                            System.err.printf("%s未匹配到directory!!!\n", record.getFileName());
                            directoryId = docMenuType.getDirectoryId();
                        } else {
                            if (directoryIdByNames.size() > 1) {
                                System.err.printf("存在多条directory记录：%s\n", directoryIdByNames.toString());
                                RcDirectory tempDirectory = new RcDirectory();
                                int tempDirectoryLength = 0;
                                for (RcDirectory rcDirectory : directoryIdByNames) {
                                    if (rcDirectory.getTreePath().split(",").length > tempDirectoryLength) {
                                        tempDirectory = rcDirectory;
                                        tempDirectoryLength = rcDirectory.getTreePath().split(",").length;
                                    }
                                }
                                finalDirectory2 = tempDirectory;
                            } else {
                                finalDirectory2 = directoryIdByNames.get(0);
                            }
                            // 规章制度需要设置flowLevel
                            rcDoc.setFlowLevel(finalDirectory2.getId());
                            String treePath = finalDirectory2.getTreePath();
                            System.err.printf("当前文件属于[%s]-[%s]-[%s]，目录树为[%s]", menuBo.getType(), menuBo.getMenuType(), menuBo.getName(), treePath);
                            directoryId = treePath.split(",")[1];
                        }
                    } else if (Objects.equals(menuBo.getType(), "生产技术文件") || Objects.equals(menuBo.getType(), "部门级规章制度")) {
                        String processSetId = record.getProcessSetId();
                        String processSetName;
                        if (StrUtil.isNotEmpty(processSetId)) {
                            processSetName = tDocCateDao.getCategoryNameString(processSetId);
                        } else {
                            System.err.printf("当前文件属于[%s]-[%s]-[%s]，processSetId为空！\n", menuBo.getType(), menuBo.getMenuType(), menuBo.getName());
                            processSetName = menuBo.getName();
                            System.err.printf(processSetName);
                        }
                        List<RcDirectory> directoryIdByNames;
                        if (Objects.equals(menuBo.getType(), "生产技术文件")) {
                            directoryIdByNames = rcDirectoryDao.getDirectoryIdByNameSCJS(processSetName);
                        } else {
                            directoryIdByNames = rcDirectoryDao.getDirectoryIdByName(processSetName, directoryType);
                        }
                        RcDirectory finalDirectory2;
                        if (CollUtil.isEmpty(directoryIdByNames)) {
                            System.err.printf("%s未匹配到directory!!!\n", record.getFileName());
                            directoryId = docMenuType.getDirectoryId();
                        } else {
                            if (directoryIdByNames.size() > 1) {
                                System.err.printf("存在多条directory记录：%s，根据上一级目录[%s]确定最终子目录结构！\n", directoryIdByNames.toString(), parentName);
                                RcDirectory directoryIdByNameAndParentName;
                                if (Objects.equals(parentName, "PFMEA") || Objects.equals(parentName, "工艺变更单")) {
                                    directoryIdByNameAndParentName = rcDirectoryDao.getDirectoryIdEqualNameAndParentName(processSetName, directoryType, parentName);
                                } else {
                                    directoryIdByNameAndParentName = rcDirectoryDao.getDirectoryIdByNameAndParentName(processSetName, directoryType, parentName);
                                }
                                System.err.printf("根据上一级目录查询成功：[%s]", directoryIdByNameAndParentName.toString());
                                finalDirectory2 = directoryIdByNameAndParentName;
                            } else {
                                finalDirectory2 = directoryIdByNames.get(0);
                            }
//                                rcDoc.setDirectoryId(finalDirectory2.getId());
//                                String treePath = finalDirectory2.getTreePath();
//                                System.err.printf("当前文件属于[%s]-[%s]-[%s]，目录树为[%s]", menuBo.getType(), menuBo.getMenuType(), menuBo.getName(), treePath);
                            directoryId = finalDirectory2.getId();
                        }
                    } else {
                        System.err.printf("当前文件属于[%s]-[%s]-[%s]，不属于上述四大类型！", menuBo.getType(), menuBo.getMenuType(), menuBo.getName());
                        directoryId = docMenuType.getDirectoryId();
                    }
                }
                rcDoc.setDirectoryId(directoryId);
                rcDoc.setDirectoryType(directoryType);
                List<RcDocAuthor> docAuthors = new ArrayList<>();
                //RcDocBase rcDocBase = new RcDocBase();
                RcDocManagerDocRegulations rcDocManagerDocRegulations = new RcDocManagerDocRegulations();
                RcDocProduction rcDocProduction = new RcDocProduction();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                //获取文件类型 当文件类型为263的时候 添加变更信息
                if (menuBo.getMenuType().equals("263")) {
                    if (record.getChangeType() == null) {
                        if (record.getChangeTypeStr().equals("部门内部")) {
                            rcDocProduction.setProChangeType("2");
                        } else if (record.getChangeTypeStr().equals("跨部门")) {
                            rcDocProduction.setProChangeType("1");
                        } else {
                            rcDocProduction.setProChangeType(null);
                        }
                    } else {
                        rcDocProduction.setProChangeType(record.getChangeType().toString());
                    }

                    rcDocProduction.setProChangeApplyDept(record.getFormulateDepartmentId().toString());
                    rcDocProduction.setProChangeAcceptDept(String.valueOf(record.getDutyDepartmentId()));
                    rcDocProduction.setProChangeApplyCode(record.getFileNo());
                    Date applyDate = simpleDateFormat.parse(record.getSubmitDate());
                    rcDocProduction.setProChangeDate(applyDate);
                    rcDocProduction.setProChangeApplyUser(record.getPreparedBy().toString());
                }
                //对应主表的ID, 同时是其他表的doc_id
                String logId = null;
                String docName = null;
                try {
                    //String rcId = FileUtil.getSnowId();
                    logId = rcId;
                    resultDto.setRocId(rcId);
                    rcDocProduction.setDocId(rcId);
                    if (record.getFileLastId() != null) {
                        String fileLastId = record.getFileLastId();
                        String[] fileLastIds = fileLastId.split(",");
                        for (String lastId : fileLastIds) {
                            RcDocBase rcDocBase = new RcDocBase();
                            rcDocBase.setDocId(rcId);
                            rcDocBase.setBaseId(lastId + FileUtil.getVersion());
                            rcDocBase.setBaseType(DocBaseTypeEnum.FILE_LAST_ID.getName());
                            rcDocBase.setId(FileUtil.getSnowId());
                            try {
                                rcDocBaseDao.insert(rcDocBase);
                            } catch (Exception e) {
                                log.error("{}, {}, 上一版本文件-插入rcBaseDao表失败：{}", menuBo, conditionParams, rcDocBase.toString(), e);
                            }
                        }

                    }
                    rcDocManagerDocRegulations.setDocId(rcId);
                    rcDoc.setId(rcId);
                    //老系统的FileName对应RC表中的doc_name
                    //老系统的FilePath对应新系统的上传对象存储后的返回路径
                    //TODO
                    //老系统的FileUploadTip尚未对应
                    //老系统的originalField尚未对应
                    //老系统的PDFFile尚未对应
                    //老系统的departmentId尚未对应
                    //老系统的DeptName尚未对应
                    //老系统的workingId尚未对应
                    //老系统的workingName尚未对应
                    //老系统的productLine尚未对应
                    ////老系统的regimePropertyId对应RC_DOC表中的DOC_SYSTEM_ID,获取到该字段后需要与字典进行映射后存放
                    String regimeId = record.getRegimePropertyId();
                    if (StrUtil.isNotEmpty(regimeId)) {
                        String relId = DocSystemIdEnum.getByCode(regimeId).getRelId();
                        if (relId == null) {
                            log.error("{}, {},当前数据获取 的relId为null{}", menuBo, conditionParams, record);
                        }
                        rcDoc.setDocSystemId(relId);
                    }

                    //老系统的FileNo与RC_DOC表中的doc_code对应
                    String docCode = record.getFileNo();
                    rcDoc.setDocCode(docCode);
                    if (docCode.startsWith("SJT") && docCode.length() >= 7) {
                        System.err.printf("当前文件编码为[%s]，需要处理\n", docCode);
                        rcDoc.setDocComCode("SJT");
                        String flagString = docCode.substring(5, 6);
                        if (flagString.matches("\\d+")) {
                            System.err.printf("当前文件编码为[%s]，第6位为数字类型\n", docCode);
                            rcDoc.setDocDeptCode(docCode.substring(3, 7));
                            rcDoc.setDocTypeCode(docCode.substring(7, 8));
                            rcDoc.setDocSnCode(docCode.substring(8));
                        } else {
                            System.err.printf("当前文件编码为[%s]，第6位为字母类型\n", docCode);
                            rcDoc.setDocDeptCode(docCode.substring(3, 5));
                            rcDoc.setDocTypeCode(docCode.substring(5, 6));
                            rcDoc.setDocSnCode(docCode.substring(6));
                        }
                    }
                    //老系统的DataForZNBMLX对应RC_DOC_PRODUCTION表中的fun_dept_type ,获取到该字段后需要与字典进行映射后存放
                    rcDocProduction.setFunDeptType(record.getDataForZNBMLX());
                    //老系统的DataForZYBMLX对应RC_DOC_PRODUCTION表中的job_dept_type ,获取到该字段后需要与字典进行映射后存放
                    rcDocProduction.setJobDeptType(record.getDataForZYBMLX());
                    //老系统的FileType尚未对应
                    //老系统的docType尚未对应
                    //老系统的edition尚未对应
                    //老系统的editionNo尚未对应
                    //老系统的effectDate对应RC表中的release_time TODO 时间的校验
                    String releaseDate = record.getReleaseDate();
                    if (StrUtil.isNotEmpty(releaseDate)) {
                        Date releaseDates = simpleDateFormat.parse(releaseDate);
                        rcDoc.setReleaseTime(releaseDates);
                    }
                    //老系统的fileVersion对应RC表中的doc_version
                    rcDoc.setDocVersion(record.getFileVersion());
                    //老系统的destroy尚未对应
                    //老系统的destroyFiled尚未对应
                    if (StrUtil.isNotEmpty(record.getDestroyFileId())) {
                        String fileLastId = record.getDestroyFileId();
                        String[] fileLastIds = fileLastId.split(",");
                        for (String lastId : fileLastIds) {
                            RcDocBase rcDocBase = new RcDocBase();
                            rcDocBase.setDocId(rcId);
                            rcDocBase.setBaseId(lastId + FileUtil.getVersion());
                            rcDocBase.setBaseType(DocBaseTypeEnum.FILE_LAST_ID.getName());
                            rcDocBase.setId(FileUtil.getSnowId());
                            try {
                                rcDocBaseDao.insert(rcDocBase);
                            } catch (Exception e) {
                                log.error("{}, {},同时废止文件-插入rcBaseDao表失败：{}", menuBo, conditionParams, rcDocBase.toString(), e);
                            }
                            System.out.printf("同时废止文件ID不为空，新增rcDocBase表记录：%s", rcDocBase.toString());
                        }

                    }
                    //老系统的release_date对应publish_time
                    if (StrUtil.isNotEmpty(record.getEffectDate())) {
                        Date effect = simpleDateFormat.parse(record.getEffectDate());
                        rcDoc.setPublishTime(effect);
                    }
                    //老系统的discardDate尚未对应
                    //老系统的deleteList尚未对应
                    //老系统的simulationDraftId尚未对应
                    //老系统approveE尚未对应
                    //老系统approveDate尚未对应
                    //老系统FirstLevel尚未对应
                    //老系统secrecyLevel与rc_doc_production表中的secrecy_level相对应 枚举类对应 TODO待定
                    rcDocProduction.setSecrecyLevel(record.getSecrecyLevel());
                    //老系统secrecyTerm尚未对应
                    //老系统FirstLevel尚未对应
                    //老系统FormulatedDepartmentId对应rc_doc表中的doc_dept_id
                    if (record.getFormulateDepartmentId() != null) {
                        rcDoc.setDocDeptId(record.getFormulateDepartmentId().toString());
                    }
                    //老系统FormulatedDepName对应rc_doc表中的doc_dept_name
                    rcDoc.setDocDeptName(record.getFormulateDepName());
                    //老系统iscontolYear尚未对应
                    //老系统rulesId尚未对应
                    //老系统rules
                    if (StrUtil.isNotEmpty(record.getRulesId())) {
                        // 如果ruleIds不为null，以逗号为分隔符，向DocBase表中插入一条COM_RELATION记录
                        String[] ruleIds = record.getRulesId().split(",");
                        log.info("获取到的rulesId为:{}", Arrays.asList(ruleIds));
                        Arrays.stream(ruleIds).filter(StrUtil::isNotEmpty).forEach(it -> {
                            RcDocBase rcDocBase = new RcDocBase();
                            rcDocBase.setDocId(rcId);
                            rcDocBase.setBaseId(it);
                            rcDocBase.setBaseType(DocBaseTypeEnum.RULE_ID.getName());
                            rcDocBase.setId(FileUtil.getSnowId());
                            try {
                                rcDocBaseDao.insert(rcDocBase);
                            } catch (Exception e) {
                                log.error("{}, {},rule文件-插入rcBaseDao表失败：{}", menuBo, conditionParams, rcDocBase.toString(), e);
                            }
                        });
                    }
                    //老系统rulesNo尚未对应
                    //老系统viewRange尚未对应
                    //老系统viewPersonnel尚未对应
                    //老系统downloadRange尚未对应
                    //老系统downloadPersonnel尚未对应
                    //老系统viewRange尚未对应
                    //老系统的status对应rc_doc表中的doc_type 3执行中 5作废 对应枚举值
                    DocStatusEnum docStatus = DocStatusEnum.getDocStatusEnum(record.getStatus().toString());
                    rcDoc.setDocType(docStatus.getName());
                    //老系统的readStatus尚未对应
                    //老系统的readStatusDesc尚未对应
                    //老系统的approveFlowId尚未对应
                    //老系统的discardFlowId尚未对应
                    //老系统的workflowApprove尚未对应
                    //老系统的workflowDiscard尚未对应
                    //老系统的scramblePath尚未对应
                    //老系统的scrambleCode尚未对应
                    //老系统的processSetId对应新系统的rc_doc表中的flow_level 对应枚举 TODO待定
//            if (record.getProcessSetId() != null) {
//                rcDoc.setFlowLevel(record.getProcessSetId().toString());
//            }
                    //老系统的unScrambleName尚未对应
                    //老系统的unScrambleText尚未对应
                    //老系统的delFlg对应rc_doc表中的delete_flag
                    rcDoc.setDeleteFlag(record.getDelFlg());
                    //老系统的uploader对应rc_doc表中的creator
                    rcDoc.setCreator(record.getUploader());
                    //老系统的insUserId尚未对应
                    //老系统的insDate对应rc_doc表中的create_time
                    SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    if (StrUtil.isNotEmpty(record.getInsDate())) {
                        Date createDate = simpleDate.parse(record.getInsDate());
                        rcDoc.setCreateTime(createDate);
                    }
                    //老系统的updUserId对应rc_doc表中的creator(creator中确定使用uploader)
                    //老系统的dataTypeColor尚未对应
                    //老系统的tenantId尚未对应
                    //老系统的menuType尚未对应
                    //老系统的subMenuType尚未对应
                    //老系统的professionPropertyId尚未对应
                    //老系统的viewProductionLineId尚未对应
                    //老系统的viewDepartmentId尚未对应
                    //老系统的suggOrQuestion尚未对应
                    //老系统的improveType尚未对应
                    //老系统的uuid尚未对应
                    //老系统的versionUrl尚未对应
                    //老系统的newFileType尚未对应
                    //老系统的versionType尚未对应
                    //老系统的keywordList尚未对应
                    //老系统的relationInfos尚未对应
                    //老系统的annexInfoList尚未对应
                    //老系统的versionList尚未对应
                    //老系统的fileLastName尚未对应
                    //老系统的processSetName尚未对应
                    //老系统的processSetStr尚未对应
                    //老系统的regimePropertyName尚未对应
                    //老系统的dateS尚未对应
                    //老系统的dateE尚未对应
                    //老系统的editionSerial尚未对应
                    //老系统的userName尚未对应
                    //老系统的userDate尚未对应
                    // 老系统的sysDepts尚未对应
                    // 老系统的fileProblemList尚未对应
                    // 老系统的approveType尚未对应
                    // 老系统的fileld尚未对应
                    // 老系统的statusName尚未对应
                    // 老系统的remark尚未对应
                    // 老系统的filennexInfo尚未对应
                    // 老系统的filAnnexName尚未对应
                    // 老系统的busiId尚未对应
                    // 老系统的examineId尚未对应
                    // 老系统的approvalUser尚未对应
                    // 老系统的fileSource尚未对应
                    // 老系统的fileTypeValue尚未对应
                    // 老系统的rulesName尚未对应
                    // 老系统的checkDTOs尚未对应
                    // 老系统的abandonedInfos尚未对应
                    //老系统的due_date对应rc_doc表中的expireTime
                    if (record.getDueDate() != null) {
                        String dueDate = record.getDueDate().toString().split(" ")[0];
                        rcDoc.setExpireDate(dueDate);
                    }
                    //TODO 老系统的dueDateDesc通过该字段找到menuType
                    //老系统的fileTypeStr尚未对应
                    //老系统的professionName通过该字段找到professionPropertyId TODO 待定
                    //老系统的firstLevelStr尚未对应
                    //老系统的secrecyLevelStr尚未对应
                    //老系统的secrecyTermStr尚未对应
                    //老系统的submitDate尚未对应
                    //老系统的auditDate尚未对应
                    //老系统的preparedBy尚未对应
                    //老系统的standardChineseDescription尚未对应
                    //老系统的standardNumber尚未对应
                    //老系统的instituteCode尚未对应
                    //老系统的active尚未对应
                    //老系统的blockFlag尚未对应
                    //老系统的mainBody尚未对应
                    //老系统的versionNumber尚未对应
                    //老系统的chineseDesc尚未对应
                    //老系统的mainBodyVersion尚未对应
                    //老系统的docTitle对应RC_doc表中的doc_name
                    //rcDoc.setDocName(record.getDocTitle()); //移除改行的映射 与上述的FileName映射冲突 本字段或覆盖


                    //老系统的professionalReview尚未对应
                    //老系统的standardizInspection尚未对应
                    //老系统的preparedByStr尚未对应
                    //老系统的menu尚未对应
                    //老系统的collect尚未对应
                    //老系统的flowApproveList尚未对应
                    //老系统的departmentIds尚未对应
                    //老系统的flowDiscardList尚未对应
                    //老系统的taskAuditUser尚未对应
                    //老系统的taskNullifyUser尚未对应
                    //老系统的jumpUrl尚未对应
                    //老系统的level尚未对应
                    //老系统的preparedBy1尚未对应
                    //老系统的preparedUserInfo信息的对应关系 暂时按照一个审批人创建
                    // List<IssUserInfo> preparedUserInfo = record.getPreparedUserInfo();
                    Type type = new TypeToken<List<IssUserInfo>>() {
                    }.getType();
                    String preparedUserInfo = record.getPreparedUserInfo();
                    if (StrUtil.isNotEmpty(preparedUserInfo)) {
                        List<IssUserInfo> prepares = gson.fromJson(preparedUserInfo, type);
                        for (IssUserInfo userInfo : prepares) {
                            if (userInfo.getUserNo() == null) {
                                System.err.println("当前prepares用户的UserNo为null, 已经跳过。" + userInfo);
                                break;
                            }
                            RcDocAuthor author = new RcDocAuthor();
                            author.setDocId(rcId);
                            author.setUserId(userInfo.getUserNo());
                            //USER_TYPE为人员字段的枚举（根据哪个字段映射枚举？）
                            //rcDocAuth.setUserType();
                            author.setUserType(DocUserTypeEnum.AUTHOR.getName());
                            docAuthors.add(author);
                        }
                    }

                    //老系统的issuer尚未对应
                    //老系统的issuer1尚未对应
                    //老系统的issUserInfos信息的对应关系 暂时按照一个审批人创建
                    String issUserInfos = record.getIssUserInfo();
                    if (StrUtil.isNotEmpty(issUserInfos)) {
                        List<IssUserInfo> issUserInfoList = gson.fromJson(issUserInfos, type);
                        for (IssUserInfo userInfo : issUserInfoList) {
                            if (userInfo.getUserNo() == null) {
                                System.err.println("当前issUserInfoList用户的UserNo为null, 已经跳过。" + userInfo);
                                break;
                            }
                            RcDocAuthor author = new RcDocAuthor();
                            author.setDocId(rcId);
                            author.setUserId(userInfo.getUserNo());
                            //USER_TYPE为人员字段的枚举（根据哪个字段映射枚举？）
                            author.setUserType(DocUserTypeEnum.SIGN.getName());
                            docAuthors.add(author);
                        }
                    }

                    //老系统的basis尚未对应
                    //老系统reviewer尚未对应
                    //老系统的reviewerUserInfo信息的对应关系 暂时按照一个审批人创建
                    String reviewerUserInfo = record.getReviewerUserInfo();
                    if (StrUtil.isNotEmpty(reviewerUserInfo)) {
                        List<IssUserInfo> reviewerUserInfoList = gson.fromJson(reviewerUserInfo, type);
                        for (IssUserInfo userInfo : reviewerUserInfoList) {
                            if (userInfo.getUserNo() == null) {
                                System.err.println("当前reviewerUserInfo用户的UserNo为null, 已经跳过。" + userInfo);
                                break;
                            }
                            RcDocAuthor author = new RcDocAuthor();
                            author.setDocId(rcId);
                            author.setUserId(userInfo.getUserNo());
                            //USER_TYPE为人员字段的枚举（根据哪个字段映射枚举？）
                            author.setUserType(DocUserTypeEnum.APPROVAL.getName());
                            docAuthors.add(author);
                        }
                    }

                    //老系统paperwork尚未对应
                    //老系统paperworkUserInfo尚未对应
                    //老系统category尚未对应
                    //老系统responsibleDepartment尚未对应
                    //老系统specialPlan尚未对应
                    //老系统admin尚未对应
                    //老系统review1尚未对应
                    //老系统issuer2尚未对应
                    //老系统preparedBy2尚未对应
                    //老系统submitFlowId尚未对应
                    //老系统submitWorkFlowApprove尚未对应
                    //老系统flowSubmitList尚未对应
                    //老系统taskSubmitUser尚未对应
                    //老系统rulesDtos尚未对应
                    //老系统flagValue尚未对应
                    //老系统flagName尚未对应
                    //老系统nextSubmitNodeKey尚未对应
                    //老系统nextUserInfos尚未对应
                    //老系统isPublish尚未对应
                    //老系统viewPermissions对应RC_USER_QUERY_INF表 todo
                    //老系统downloadPermissions对应RC_USER_QUERY_INF表 todo
                    //老系统dataForisCurle尚未对应
                    //老系统unUserFulResult尚未对应
                    //老系统的solidDoc尚未对应
                    //老系统的changeType尚未对应
                    //老系统的isProductPermissions尚未对应
                    //老系统的topCateId尚未对应
                    //老系统的topCateNameStr尚未对应
                    //老系统的topCateName尚未对应
                    //老系统的dutyDepartmentId尚未对应
                    //老系统的dutyDepartmentName尚未对应
                    //老系统的reviewChange尚未对应
                    //老系统的proReviewChange尚未对应
                    //老系统的submitType尚未对应
                    //老系统的reviseWorkFlowApprove尚未对应
                    //老系统的reviseWorkFlowId尚未对应
                    //老系统的nullifyPaperworks尚未对应
                    //老系统的nullifyPaperwork尚未对应
                    //老系统的nullifyExplain尚未对应
                    //老系统的belongFileName尚未对应
                    //老系统的belongFilePath尚未对应
                    //老系统的annexStr尚未对应
                    //老系统的mediumStr尚未对应
                    //老系统的mediumName尚未对应
                    //老系统的mediumType尚未对应
                    //老系统的belongFileNo尚未对应
                    //老系统的instituteNameList尚未对应
                    //老系统的instituteNameStr尚未对应
                    //老系统的instituteCodeStr尚未对应
                    //老系统的companyDirector尚未对应
                    //老系统的companyDirectorUserInfo尚未对应
                    //老系统的mediumLocation尚未对应
                    //老系统的archiveDateFrom尚未对应
                    //老系统的rulesMenutype尚未对应
                    //老系统的siRulesCompany尚未对应
                    //老系统的phone尚未对应
                    //老系统的isOwnDepartment尚未对应
                    //老系统的proReviewChange1尚未对应
                    //老系统的changeTypeStr尚未对应
                    //老系统的pilotTypeStr尚未对应
                    //老系统的applyDeptNames尚未对应
                    //老系统的applyDeptDto尚未对应
                    //老系统的applyDeptDtoShow尚未对应
                    //老系统的rulesPath尚未对应
                    //老系统的rulesUploadTop尚未对应
                    //老系统的isOwnerUser尚未对应
                    //老系统的ProfessionalReviewName尚未对应
                    //老系统的docTypeName尚未对应
                    //老系统的rulesJumpUrl尚未对应
                    //老系统的fieldChanged尚未对应
                    //老系统的dueDateStr尚未对应
                    //老系统的submitDateStr尚未对应
                    //老系统的insDateStr尚未对应
                    //老系统的effectDateStr尚未对应
                    //老系统的discardDateStr尚未对应
                    //老系统的releaseDateStr尚未对应
                    //老系统的approveDateStr尚未对应
                    //老系统的auditDateStr尚未对应
                    RcBpmnProcess rcBpmnProcess = new RcBpmnProcess();
                    rcBpmnProcess.setBpmnId(rcBpmnProcess.getId());
                    rcDoc.setApproveId(rcBpmnProcess.getBpmnId());
                    // rcDoc.setDocName();
                    // 下载主文件
                    DownloadFileInfo downloadFileInfo = new DownloadFileInfo();
                    String fileNameStr = record.getFileName() + ".docx";
                    downloadFileInfo.setFileName(fileNameStr);
                    downloadFileInfo.setFilePath(record.getFilePath());
                    String fileName = FileUtil.downloadFile(token, downloadFileInfo, String.valueOf(record.getId()));
                    rcDoc.setDocName(fileName.substring(0, fileName.lastIndexOf(".")));
                    try {
                        rcDocDao.insert(rcDoc);
                    } catch (DuplicateKeyException e) {
                        log.error("{}, {}, {} 插入rcDoc主表异常, 该条记录不再继续同步", menuBo, conditionParams, record.getFileName(), e);
                        return resultDto;
                    }
                    // rcDocAttachmentDao.insert(rcDocAttachment);
                    //跑全量的时候放开insert
                    try {
                        rcDocProductionDao.insert(rcDocProduction);
                    } catch (Exception e) {
                        log.error("{}, {},插入rcDocProduction表失败：{}", menuBo, conditionParams, rcDocProduction.toString(), e);
                    }
                    //跑存量用update
                    //rcDocProductionDao.updateExist(rcDocProduction);
                    // rcDocBaseDao.insert(rcDocBase);
                    for (RcDocAuthor author : docAuthors) {
                        try {
                            rcDocAuthorDao.insert(author);
                        } catch (Exception e) {
                            log.error("{}, {},插入rcDocAuthor表失败：{}", menuBo, conditionParams, author.toString(), e);
                        }
                    }
                    // 上传主文件，先注释掉
                    FileOperatorParams fileOperatorParams = new FileOperatorParams();
                    fileOperatorParams.setDocName(fileName);
                    fileOperatorParams.setDocId(rcId);
                    fileOperatorParams.setDirectoryType(rcDoc.getDirectoryType());
                    boolean isUploaded = FileUtil.uploadMainFile(fileOperatorParams, String.valueOf(record.getId()));
                    if (!isUploaded) {
                        log.error("上传主文档-{}失败：类型{},{}", record.getFileName(), menuBo, conditionParams);
                    }
                    // 根据老系统的文件id获取附件信息并入库
                    getAnnexFilesAndUpload(String.valueOf(record.getId()), token, rcId, menuBo, conditionParams, record.getFileName());
                    try {
                        rcDocManagerDocRegulationsDao.insert(rcDocManagerDocRegulations);
                    } catch (Exception e) {
                        log.error("{}, {},插入rcDocManagerDocRegulations表失败：{}", menuBo, conditionParams, rcDocManagerDocRegulations.toString(), e);
                    }
                    String s = RequestUtil.syncEs(rcId);
                    //同步审批记录
                    String oldDocId = record.getId().toString();
                    List<RecordFromDB> approvalList = approvalRecordDAO.getApprovalList(oldDocId);
                    System.err.println("同步审批记录查询到的信息:" + approvalList);
                    rcBpmnProcess.setRelationId(rcId);
                    rcBpmnProcess.setRelationType("DOC");
                    rcBpmnProcess.setProcessStatus("COMPLETED");
                    Date start = new Date();
                    rcBpmnProcess.setUpdateTime(start);
                    rcBpmnProcess.setCreateTime(start);
                    try {
                        approvalRecordDAO.saveRcBpmnProcess(rcBpmnProcess);
                    } catch (Exception e) {
                        log.error("{}, {},插入approvalRecordDAO表失败-1：{}", menuBo, conditionParams, rcBpmnProcess.toString(), e);
                    }
                    for (RecordFromDB recordFromDB : approvalList) {
                        RcBpmnTask rcBpmnTask = new RcBpmnTask();
                        rcBpmnTask.setBpmnId(rcBpmnProcess.getBpmnId());
                        rcBpmnTask.setProcessId(rcBpmnProcess.getId());
                        String code = recordFromDB.getStatus().toString();
                        String statusByCode = ApprovalTypeEnum.getStatusByCode(code);
                        rcBpmnTask.setTaskType("APPROVAL");
                        rcBpmnTask.setApprovalAction(statusByCode);
                        rcBpmnTask.setTaskStatus("COMPLETED");
                        if (null != recordFromDB.getComment()) {
                            rcBpmnTask.setApprovalOpinions(recordFromDB.getComment().replaceAll("<p>", "").replaceAll("</p>", ""));
                        }
                        if (recordFromDB.getUserInfo() != null) {
                            String[] split = recordFromDB.getUserInfo().split("/");
                            rcBpmnTask.setApprovalUserId(split[split.length - 1]);
                        } else {
                            rcBpmnTask.setApprovalUserId(null);
                        }
                        rcBpmnTask.setCreateDate(recordFromDB.getTime());
                        if (null != rcBpmnTask.getApprovalOpinions()) {
                            rcBpmnTask.setApprovalOpinions(rcBpmnTask.getApprovalOpinions().replaceAll("<p>", "").replaceAll("</p>", ""));

                        }
                        //存库
                        try {
                            approvalRecordDAO.saveRcBpmnTask(rcBpmnTask);
                        } catch (Exception e) {
                            log.error("{}, {},插入approvalRecordDAO表失败-2：{}", menuBo, conditionParams, rcBpmnProcess.toString(), e);
                        }
                    }
                    log.info("同步结果：文档[{}]-docId[{}]同步完成，{}, {},", docName, logId, menuBo, conditionParams);
                    break;
                } catch (Exception e) {
                    log.error("同步结果：文档[{}]-docId[{}]同步失败，开始第{}次重试同步", docName, logId, i + 1);
                    log.error("同步过程中捕获到的异常:", e);
                    processSyncFailedRecord(logId);
                    if (i == 4) {
                        break;
                    }
                    log.error("第{}次同步失败，跳过本次数据同步，文档[{}]-docId[{}]", i + 1, docName, logId);
                    resultDto.setSyncFailed(true);
                }
            }

        }
        return resultDto;

    }

    private boolean isSkip(Integer id) {
        List<String> skipIds = Arrays.asList("13848", "15875", "16147", "16857", "17053", "17111", "17153", "17232", "20307", "20308", "20309", "20311", "20312", "2107", "2119", "2122", "2159", "3695", "5361", "5904", "6229");
        return skipIds.contains(String.valueOf(id));
    }


    public void getAnnexFilesAndUpload(String fileId, String token, String rcId, MenuBO menuBo, ConditionParams conditionParams, String recordName) throws Exception {
        ResponseBody responseBody = RequestUtil.getAnnexFileList(fileId, token);
        Gson gson = new Gson();
        ResponseAnnexFileDTO responseAnnexFileDTO = gson.fromJson(responseBody.string(), ResponseAnnexFileDTO.class);
        responseBody.close();
        List<ResponseAnnexFileDTO.DataDTO> responseAnnexFileDataDTO = responseAnnexFileDTO.getData();
        responseAnnexFileDataDTO.forEach(it -> {
            String fileAnnexName = "";
            try {
                fileAnnexName = it.getFileAnnexName();
                if (StrUtil.isEmpty(fileAnnexName)) {
                    System.err.println(recordName + "的附件文档内容为空！");
                } else {
                    DownloadFileInfo fileDownloadInfo = new DownloadFileInfo();
                    fileDownloadInfo.setFilePath(it.getFileAnnexPath());
                    fileDownloadInfo.setFileName(fileAnnexName);
                    String downloadName = FileUtil.downloadFile(token, fileDownloadInfo, fileId);
                    FileOperatorParams fileOperatorParams = new FileOperatorParams();
                    fileOperatorParams.setDocId(rcId);
                    fileOperatorParams.setDocName(downloadName);
                    boolean isUploaded = FileUtil.uploadAttachmentFile(fileOperatorParams, fileId);
                    if (!isUploaded) {
                        log.error("{}的附件文件{}上传失败1：当前入参：{}-{}", recordName, downloadName, menuBo, conditionParams);
                    }
                }
            } catch (Exception e) {
//                throw new RuntimeException(e);
                log.error("{}的附件文件{}上传失败：当前入参2：{}-{}", recordName, fileAnnexName, menuBo, conditionParams);
            }
        });
    }


    public static void main(String[] args) throws Exception {
        String s = "{\"code\":0,\"msg\":null,\"data\":{\"listSearch\":[{\"value\":\"3\",\"label\":\"执行中\",\"sort\":0,\"count\":1589},{\"value\":\"91\",\"label\":\"未读\",\"sort\":1,\"count\":1585},{\"value\":\"92\",\"label\":\"已读\",\"sort\":2,\"count\":0},{\"value\":\"2\",\"label\":\"编审批中\",\"sort\":5,\"count\":0},{\"value\":\"5\",\"label\":\"废止\",\"sort\":6,\"count\":1},{\"value\":\"99\",\"label\":\"我的新增\",\"sort\":7,\"count\":0}],\"page\":{\"records\":[{\"id\":20122,\"fileName\":\"HSPC-2024082201首钢供奥通大有原油储备库项目用L360M热轧钢板技术协议\",\"fileLastId\":null,\"filePath\":\"/doc/sfiles/download/125866\",\"fileUploadTip\":\"125866\",\"originalFileId\":\"125866\",\"pdfFileId\":null,\"departmentId\":null,\"deptName\":null,\"workingId\":null,\"workingName\":null,\"productLine\":null,\"regimePropertyId\":null,\"fileNo\":\"HSPC-2024082201\",\"dataForZNBMLX\":\"\",\"dataForZYBMLX\":\"\",\"fileType\":null,\"docType\":null,\"edition\":\"VN1919f147841\",\"editionNo\":\"1919f4b65f5\",\"fileVersion\":null,\"effectDate\":\"2024-08-30\",\"destroyFileId\":null,\"destroyFileName\":null,\"releaseDate\":null,\"discardDate\":null,\"deleteList\":null,\"simulationDraftId\":null,\"approveE\":null,\"approveDate\":null,\"firstLevel\":null,\"secrecyLevel\":null,\"secrecyTerm\":\"\",\"simulationDraft\":null,\"formulateDepartmentId\":null,\"formulateDepName\":null,\"iscontolYear\":null,\"rulesId\":null,\"rules\":null,\"rulesNo\":null,\"viewRange\":null,\"viewPersonnel\":null,\"downloadRange\":null,\"downloadPersonnel\":null,\"status\":3,\"readStatus\":\"0\",\"readStatusDesc\":\"未读\",\"approveFlowId\":null,\"discardFlowId\":null,\"workFlowApprove\":null,\"workFlowDiscard\":null,\"unscramblePath\":null,\"unscrambleCode\":null,\"processSetId\":null,\"unscrambleName\":null,\"unscrambleText\":null,\"delFlg\":0,\"uploader\":null,\"insUserId\":9999,\"insDate\":\"2024-08-30 01:00:04\",\"updUserId\":10000,\"updDate\":\"2024-08-30 02:00:03\",\"dateTypeColor\":4,\"tenantId\":1,\"menuType\":917,\"submenuType\":null,\"professionPropertyId\":null,\"viewProductionLineId\":null,\"viewDepartmentId\":null,\"suggOrQuestion\":null,\"improveType\":null,\"uuId\":null,\"versionUrl\":null,\"newFileType\":null,\"versionType\":null,\"keywordList\":null,\"relationInfos\":null,\"annexInfoList\":null,\"versionList\":null,\"fileLastName\":null,\"processSetName\":null,\"processSetStr\":null,\"regimePropertyName\":null,\"dateS\":null,\"dateE\":null,\"editionSerial\":\"V1.00\",\"userName\":\"10084893\",\"userDate\":null,\"sysDepts\":null,\"fileProblemList\":null,\"approveType\":null,\"fileId\":null,\"statusName\":\"执行/未读\",\"remake\":null,\"filennexInfo\":null,\"fileAnnexName\":null,\"busiId\":null,\"examineUser\":null,\"approvalUser\":null,\"fileSource\":null,\"fileTypeValue\":null,\"rulesName\":null,\"checkDtos\":null,\"abandonedInfos\":null,\"dueDate\":null,\"dueDateDesc\":\"\",\"fileTypeStr\":\"生产技术文件 / 外部标准 / 产品交货标准\",\"professionName\":null,\"firstLevelStr\":null,\"secrecyLevelStr\":null,\"secrecyTermStr\":null,\"submitDate\":null,\"auditDate\":null,\"preparedBy\":null,\"standardChineseDescription\":\"首钢供奥通大有原油储备库项目用L360M热轧钢板技术协议\",\"standardNumber\":\"HSPC-2024082201\",\"instituteCode\":\"U\",\"active\":\"0\",\"blockFlag\":\"0\",\"mainBody\":\"HSPC-2024082201\",\"versionNo\":null,\"chineseDesc\":\"首钢供奥通大有原油储备库项目用L360M热轧钢板技术协议\",\"mainBodyVersion\":\"HSPC-2024082201\",\"docTitle\":\"HSPC-2024082201首钢供奥通大有原油储备库项目用L360M热轧钢板技术协议\",\"professionalReview\":null,\"standardizInspection\":null,\"preparedByStr\":null,\"menu\":null,\"collect\":2,\"flowApproveList\":null,\"departmentIds\":null,\"flowDiscardList\":null,\"taskAuditUser\":null,\"taskNullifyUser\":null,\"jumpUrl\":null,\"level\":null,\"preparedBy1\":null,\"preparedUserInfo\":null,\"issuer\":null,\"issuer1\":null,\"issUserInfo\":null,\"basis\":null,\"reviewer\":null,\"reviewerUserInfo\":null,\"paperwork\":null,\"paperworkUserInfo\":null,\"category\":null,\"responsibleDepartment\":null,\"specialPlan\":null,\"admin\":null,\"reviewer1\":null,\"issuer2\":null,\"preparedBy2\":null,\"submitFlowId\":null,\"submitWorkFlowApprove\":null,\"flowSubmitList\":null,\"taskSubmitUser\":null,\"rulesDtos\":null,\"flagValue\":null,\"flagName\":null,\"nextSubmitNodeKey\":null,\"nextUserInfos\":null,\"isPublish\":false,\"viewPermissions\":null,\"downloadPermissions\":null,\"dataForisCurle\":null,\"unUserfulResult\":null,\"solidDoc\":null,\"changeType\":null,\"isProductPermissions\":null,\"topCateId\":null,\"topCateNameStr\":null,\"topCateName\":null,\"dutyDepartmentId\":null,\"dutyDepartmentName\":null,\"reviewChange\":\"\",\"proReviewChange\":\"\",\"submitType\":null,\"reviseWorkFlowApprove\":\"\",\"reviseWorkFlowId\":\"\",\"nullifyPaperworks\":null,\"nullifyPaperwork\":\"\",\"nullifyExplain\":\"\",\"belongFileName\":null,\"belongFilePath\":null,\"annexStr\":null,\"mediumStr\":null,\"mediumName\":null,\"mediumType\":null,\"belongFileNo\":null,\"instituteNameList\":[\"外来企标或供货技术条件\"],\"instituteNameStr\":\"外来企标或供货技术条件\",\"instituteCodeStr\":\"U\",\"companyDirector\":null,\"companyDirectorUserInfo\":null,\"mediumLocation\":null,\"archiveDateFrom\":null,\"rulesMenutype\":null,\"isRulesCompany\":null,\"phone\":null,\"isOwnDepartment\":null,\"proReviewChange1\":null,\"changeTypeStr\":\"部门内部\",\"pilotTypeStr\":null,\"applyDeptNames\":null,\"applyDeptDto\":null,\"applyDeptDtoShow\":null,\"rulesPath\":null,\"rulesUploadTip\":null,\"isOwnUser\":null,\"professionalReviewName\":null,\"docTypeName\":null,\"rulesJumpUrl\":null,\"fileChanged\":false,\"insDateStr\":\"2024-08-30\",\"auditDateStr\":\"\",\"discardDateStr\":\"\",\"submitDateStr\":\"\",\"effectDateStr\":\"2024-08-30\",\"approveDateStr\":\"\",\"releaseDateStr\":\"\",\"dueDateStr\":\"\"}],\"total\":1589,\"size\":1,\"current\":7,\"orders\":[],\"hitCount\":false,\"searchCount\":true,\"pages\":1589}}}\n";
        ApplyMappingService a = new ApplyMappingService();
//        a.applyMapping(s, "222", DocType.MANAGE_MANUAL);
    }

    public void deleteAll(String idSuffix) {
        List<RcDoc> rcDocs = rcDocDao.selectAll(idSuffix);
        System.err.printf("共发现[%s]条需要删除的记录", rcDocs.size());
        rcDocs.forEach(it -> processSyncFailedRecord(it.getId()));
    }

    @SneakyThrows
    public void processSyncFailedRecord(String rcId) {
        try {
            rcDocDao.deleteById(rcId);
        } catch (Exception e) {
            log.error("删除[{}]文件数据库库记录失败！", rcId);
        }
        try {
            String esInfo = RequestUtil.getEsDocById(rcId);
            System.err.println(esInfo);
            if (StrUtil.isEmpty(esInfo)) {
                System.err.printf("当前docId[%s]的ES信息为空%n", rcId);
                return;
            }
            EsBO esBO;
            Gson gson = new Gson();
            esBO = gson.fromJson(esInfo, EsBO.class);
            String esId = esBO.getId();
            String delInfo = RequestUtil.deleteEsById(esId);
            System.err.println("删除ES信息结果，delInfo:" + delInfo);
//            rcDocDao.deleteById(rcId);
        } catch (Exception e) {
            log.error("删除[{}]文件ES记录失败！", rcId);
        }
        Thread.sleep(1000);

    }

    public void selectAll() {
        List<RcDoc> rcDocs = rcDocDao.selectAll(FileUtil.VERSION_SUFFIX);
        rcDocs.forEach(it -> {
            String esInfo = null;
            try {
                esInfo = RequestUtil.getEsDocById(it.getId());
            } catch (IOException e) {
                System.err.println("获取ES信息异常：" + e.getMessage());
            }
            if (StrUtil.isEmpty(esInfo)) {
                System.err.printf("当前docId[%s]的ES信息为空%n", it.getId());
            } else {
                System.err.println(esInfo);
            }
        });
    }
}
